<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 订单接口
 * @author www.dingwei.cn
 */
class Order extends MY_Controller {
	
	/**
	 * 设置模块
	 * @var AdmSettingModel
	 */
	public $mSetting;
    /**
     * @var ConsumerOrderModel
     */
	public $mOrder;

	public $mDlnOrder;

	public function __construct(){
		parent::__construct();

	}

    /**
     * 处理旧订单数据
     */
    public function operation(){


//        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
//        $this->db->select('id, param');
//        $data = $this->mOrder->getAll($this->mOrder->tbOrder);
//        $tData = [];
//        foreach ($data as $v){
//            $param = json_decode($v['param'], true);
//
//            $tData[] = [
//                'id' => $v['id'],
//                'bonus' => $param['bonus'],
//                'lunch_box_fee' => $param['lunch_box_fee'],
//                'merchant_discount' => sprintf('%.2f', $param['full_cut'] + $param['coupon'] + $param['first_order_reduce']),
//                'postal_card' => $param['postal_card'],
//            ];
//        }
//
//        if(!($this->mOrder->saveBatch($tData, 0, array(), 'id'))){
//            $this->appReturn(0, '失败');
//        }

        //店铺广告
//        $this->db->select('id,shop_ads');
//        $merchant = $this->mUser->getAll($this->mUser->tbUser);
//        $mData = [];
//        foreach ($merchant as $value){
//            $ads = json_decode($value['shop_ads'], true);
//            if($ads){
//                $temp = [];
//                foreach ($ads as $vv){
//                    $temp[] = ['id' => '', 'productName' => '', 'adpic' => $vv];
//                }
//                if($temp){
//                    $mData[] = [
//                        'id' => $value['id'],
//                        'shop_ads' => json_encode($temp),
//                    ];
//                }
//            }
//
//        }
//       $query =  $this->mUser->updateBatch($this->mUser->tbUser, $mData, 'id');
//        if(!$query){
//            $this->appReturn(0, '失败1');
//        }
//        $this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
//        $this->db->select('id,nickname,mobile')
//                ->where('nickname is null');
//        $consumer = $this->mConsumer->getAll($this->mConsumer->tbUser);
//        $cData = [];
//        foreach ($consumer as $con){
//            $cData[] = [
//                'id' => $con['id'],
//                'nickname' => substr($con['mobile'],0,3).'****'.substr($con['mobile'], -4),
//            ];
//        }
//        $query =  $this->mConsumer->updateBatch($this->mConsumer->tbUser, $cData, 'id');
//        if(!$query){
//            $this->appReturn(0, '失败1');
//        }
        $this->appReturn(1, '成功');
    }

    /**
     *订单管理
     */
    public function orderList(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        //表单验证
        $vConf = array(
            array('status', '状态', 'required|in_list[0,1,2,3,4]'),
            array('expense_type', '订单类型', 'required|in_list[1,2]'),
            array('page', '页码', 'required|is_natural_no_zero')
        );
        $this->formDataValidation($vConf);

        $page = (int)post('page');
        $expense_type = post('expense_type');
        $status = post('status');

        $tA = $this->mOrder->appGetMerchantOrderList($this->userId, $expense_type, $status, $page, false);
        $orderIds = array();//平台配送
        foreach ($tA as $value){
            if($value['expense_type'] == 1 && $value['shipping_type'] == 2 && !in_array($value['id'], $orderIds)){
                $orderIds[] = $value['id'];
            }
        }
        //获取配送员信息
        $deliveryman = array();
        if($orderIds){
            $this->loadModel('DlnOrderModel', 'mDlnOrder', 'deliveryman');
            $deliveryman = $this->mDlnOrder->getDeliverymanInfoByOrderIds($orderIds);

        }
        /**
         * 订单数据
         */
//        p($tA);
        $shipping_info = (object)array();
        foreach ($tA as $k=>&$v){

            $v['expect_take_time'] = ((int)$v['pay_time'] + (int)getCustomConfig('expect_take_time')*60).'';//接单有效时间
            if($v['product_count'] > 1){
                $tA[$k]['title'] = $tA[$k]['name'].'等'.$v['product_count'].'件商品';
            }
            $shipping_info  = (object)array();
            if($v['shipping_type'] == 1){//商家配送
                $shipping_info = array(
                    'portrait' => $this->userPortrait,
                    'name' => $this->userName,
                    'mobile' => $this->userMobile,
                    'status' => '',
                );
            }
            elseif ($v['shipping_type'] == 2){//平台配送
                $tInfo = isset($deliveryman[$v['id']])?$deliveryman[$v['id']]:array();
                if($tInfo){
                    $shipping_info = array(
                        'portrait' => $tInfo['portrait'],
                        'name' => $tInfo['name'],
                        'mobile' => $tInfo['mobile'],
                        'status' => $tInfo['status_str'],
                    );
                }
            }else{
                $v['shipping_type'] = '0';
            }
            $v['shipping_info'] = $shipping_info;
        }
        $this->appReturn(1, '', $tA);
    }

    /**
     * 订单详情
     */
    public function orderDetail(){

        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $id = (int)post('id');

        $verification_code = trim(post('verification_code'));

        if(!$id && !$verification_code ){
            $this->appReturn(0,'订单id或核销码必须');
        }
        if(!is_numeric($id)){
            $this->appReturn(0, '订单id必须是大于不等于0的整数');
        }

        //订单信息
        $detail = $this->mOrder->getInfo($id, 0, $this->userId, false, $verification_code);

        if(!$detail){
            $this->appReturn(0, '订单不存在');
        }

        $proData = array();
        if(isset($detail['param']) && $detail['param']){
            foreach ($detail['param'] as $k=>$v){
                $v = sprintf('%.2f', $v);
                if($k == 'bonus' && $v > 0){
                    $proData[] = array('keyword' => '红包', 'money' => '-￥'.$v);
                }elseif ($k == 'coupon' && $v > 0){
                    $proData[] = array('keyword' => '代金券', 'money' => '-￥'.$v);
                }elseif ($k == 'first_order_reduce' && $v > 0){
                    $proData[] = array('keyword' => '商家首单减免', 'money' =>'-￥'.$v);
                }elseif ($k == 'full_cut' && $v > 0){
                    $proData[] = array('keyword' => '满减活动', 'money' => '-￥'.$v);
                }elseif ($k == 'lunch_box_fee' && $v > 0){
                    $proData[] = array('keyword' => '打包费', 'money' => '￥'.$v);
                }elseif ($k == 'postal_card' && $v > 0){
                    $proData[] = array('keyword' => '包邮卡', 'money' => '-￥'.$v);
                }
            }
        }
        //配送费
        if($detail['expense_type'] == 1){
            $proData[] = array('keyword' => '配送费', 'money' => '￥'.$detail['shipping_fee']);
        }

        //商品信息
        $productList = $this->mOrder->getOrderProductList($detail['id'], 0, $this->userId);
        if(!$productList){
            $this->appReturn(0, '订单不存在');
        }

        //改变消息状态
        $this->loadModel('MerchantMessageModel', 'mMessage');
        $message = $this->mMessage->getInfo(0, $this->userId, $detail['id']);
        if ($message) {
            // 添加消息查看记录
            if ($message['viewed'] == 1) {
                $messageData = array(
                    'merchant_id' => $this->userId,
                    'message_id' => $message['id'],
                    'order_id' => $detail['id'],
                    'is_delete' => 1,
                    'addtime' => time(),
                );

                $viewed = $this->mMessage->saveView($messageData);
                if (!$viewed) {
                    $this->appReturn(0, '添加消息查看记录失败');
                }
            }
        }
        //收益
        $income = array(
            array('keyword' => '用户实付','money' =>'￥'.$detail['reality_amount']),
            array('keyword' => '平台服务费','money' =>'￥-'.sprintf('%.2f', $detail['web_service_amount'])),
        );
        //获取配送员信息
        $shipping_info = (object)array();
        if($detail['expense_type'] == 1){
            if($detail['shipping_type'] == 2){//平台配送
                $income[] = array('keyword' => '配送费','money' =>'￥-'.$detail['shipping_fee']);
            }

            if($detail['shipping_type'] == 1){//商家配送
                $detail['merchant_income'] += $detail['shipping_fee'];
                $shipping_info = array(
                    'portrait' => $this->userPortrait,
                    'name' => $this->userName,
                    'mobile' => $this->userMobile,
                    'status' => '',
                );
            }
            if ($detail['shipping_type'] == 2){//平台配送
                $this->loadModel('DlnOrderModel', 'mDlnOrder', 'deliveryman');
                $deliveryman = $this->mDlnOrder->getDeliverymanInfoByOrderIds(array($id));

                $tInfo = isset($deliveryman[$id])?$deliveryman[$id]:array();
                if($tInfo){
                    $shipping_info = array(
                        'portrait' => $tInfo['portrait'],
                        'name' => $tInfo['name'],
                        'mobile' => $tInfo['mobile'],
                        'status' => $tInfo['status_str'],
                    );
                }
            }
        }
        //打包费
        $count = '#'.$detail['merchant_day_index'];
        $n = (strtotime(date('Y').'-'.$detail['expect_arrive_time']) - time()) / 60;
        if ($n > getCustomConfig('arrive_time')){
            $count .= '预订单';
        }

        $aData = array(
            'id' => $detail['id'],
            'count' => $count,
            'percent' => 0,
            'change_amount_desc' => '',
            'code' => $detail['code'],
            'merchant' => $detail['merchant'],
            'portrait' => $detail['portrait'],
            'consumer_mobile' => $detail['consumer_mobile'],
            'consumer_portrait' => $detail['consumer_portrait'],
            'consumer' => $detail['consumer'],
            'status' => $detail['status'],
            'status_str' => $detail['status_str'],
            'tips' => $detail['tips'],
            'expect_take_time' => $detail['expect_take_time'],//接单有效时间
            'product_amount' => $detail['product_amount'],
            'change_amount' => $detail['change_amount'],
            'total_amount' => $detail['total_amount'],
            'reality_amount' => $detail['reality_amount'],
            'remark' => $detail['remark'],
            'contacts' => $detail['contacts']?$detail['contacts']:'',
            'mobile' => $detail['mobile']?$detail['mobile']:'',
            'province' => $detail['province'],
            'city' => $detail['city'],
            'address_all' => $detail['address_all'],
            'pay_type_str' => $detail['pay_type_str'],
            'shipping_type' => $detail['shipping_type'],
            'expense_type' => $detail['expense_type'],
            'expense_type_str' => $detail['expense_type_str'],
            'addtime' => substr($detail['addtime'], 0, -3),
            'arrivetime' => substr($detail['expect_arrive_time'], 0, -3),//送达时间
            'web_service_amount' => $detail['web_service_amount'].'',
            'merchant_refound' => $detail['merchant_income'].'',
            'verification_bar_code' => $detail['verification_bar_code'],
            'verification_code' => $detail['verification_code'],
            'shortage_handing' => $detail['shortage_handing'],
            'param' => $proData,
            'income' => $income,
            'shipping_info' => $shipping_info,
            'product' => $productList,
        );

        //退差价
        $percent = $this->mSetting->get('change_order_percent');
        if($detail['status'] == 3 && $percent && $detail['change_amount'] <= 0){
            $aData['percent'] = $percent;
            $aData['change_amount_desc'] = '每笔订单根据实际情况可能存在差异，您可对本订单调整一次实际价格，最高不超过商品总价的'.$percent.'%';
        }
        $this->appReturn(1, '', $aData);
    }

    /**
     * 获取订单跟踪信息
     */
    public function orderTracking(){

        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        //表单验证
        $vConf = array(
            array('order_id', '订单id', 'required'),
        );
        $this->formDataValidation($vConf);

        $orderId = post('order_id');

        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $tA = $this->mOrder->getInfo($orderId, 0, $this->userId);
        if ( ! $tA){
            $this->appReturn(0, '订单不存在');
        }
        if(!in_array($tA['status'], array(3,4,5)) || $tA['shipping_type'] != 2){
            $this->appReturn(0, '暂无配送信息');
        }
        //配送信息
        $traces = array();
        //获取配送信息
        $this->loadModel('DlnOrderModel', 'mDlnOrder', 'deliveryman');
        $dlnOrder = $this->mDlnOrder->getDeliverymanInfoByOrderIds(array($orderId));
        $dlnOrder = $dlnOrder[$orderId];
        if($dlnOrder['status'] == 1){
            $traces[] = array('status' => '配送员'.$dlnOrder['status_str'],'time' => date('m-d H:i',time()));
        }elseif ($dlnOrder['status'] == 2){
            $traces[] = array('status' => '配送员'.$dlnOrder['status_str'],'time' => date('m-d H:i',time()));
            $traces[] = array('status' => '配送员已接单','time' => $dlnOrder['addtime']);
        }
        elseif ($dlnOrder['status'] == 3){
            $traces[] = array('status' => '配送员'.$dlnOrder['status_str'],'time' => date('m-d H:i',time()));
            $traces[] = array('status' => '配送员已取单','time' => $dlnOrder['pickup_time']);
            $traces[] = array('status' => '配送员已接单','time' => $dlnOrder['addtime']);
        }elseif ($dlnOrder['status'] == 4){
            $traces[] = array('status' => '配送员已完成','time' => $dlnOrder['complete_time']);
            $traces[] = array('status' => '配送员已取单','time' => $dlnOrder['pickup_time']);
            $traces[] = array('status' => '配送员已接单','time' => $dlnOrder['addtime']);
        }
        $traces[] = array('status' => '商家已接单','time' => date('m-d H:i',$tA['merchant_take_time']));

        $ak = $this->mSett->get('map_key','deliveryman');

        $html = $this->view('order/shopper_details',[
                'ak'=>$ak,
                'delivery_latitude'=>$dlnOrder['status'] == 4?$tA['latitude']:$dlnOrder['latitude'],
                'delivery_longitude'=>$dlnOrder['status'] == 4?$tA['longitude']:$dlnOrder['longitude'],
                'shop_longitude'=>$tA['shop_longitude'],
                'shop_latitude'=>$tA['shop_latitude'],
                'send_to_latitude'=>$tA['latitude'],
                'send_to_longitude'=>$tA['longitude'],
                'Traces'=>$traces,
               ]
            ,0,0,0,true);

        $this->appReturn(1, '', $html);
    }

    /**
     * 物流公司
     */
    public function shippingCompany(){
        $this->loadModel('AdmShippingModel', 'mShipping', 'admin');

        $data = $this->mShipping->getList();

        $this->appReturn(1, '', $data);
    }

    /**
     * 订单删除（已完成订单）
     */
    public function delOrder(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        //表单验证
        $vConf = array(
            array('id', '订单id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');

        //订单信息
        $info = $this->mOrder->getInfo($id, 0, $this->userId, true);
        if(!$info){
            $this->appReturn(0, '订单不存在');
        }

        if( !in_array($info['status'], array(5,6,7))){
            $this->appReturn(0, '该订单不能删除');
        }

        //更改订单
        if(!($this->mOrder->save(array('is_merchant_delete' => 2), 0,$id))){
            $this->appReturn(0, '删除失败');
        }

        $this->appReturn(1, '删除成功');
    }
    public function time(){
        $merchant = 30;
        $deliveryman = 10;
        $take = 10;
        $start = '10:30';
        $end = '12:30';
        for($i=strtotime($start) ;$i<=strtotime($end) ; $i=$i+60*20){
            $buff[]=date("H:i:s",$i);
        }
        p($buff);
    }
    /**
     * 调价
     */
    public function changePrice(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        //表单验证
        $vConf = array(
            array('id', '订单id', 'required|is_natural_no_zero'),
            array('amount', '订单金额', 'required|is_numeric'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');
        $amount = trim(post('amount'));
        //订单信息
        $info = $this->mOrder->getInfo($id, 0, $this->userId, true);
        if($info['status'] != 3){
            $this->appReturn(0, '该订单不符合调价');
        }
        if($info['change_amount'] > 0){
            $this->appReturn(0, '该订单已成功调价,请勿重复操作');
        }
        if($info['product_amount'] < $amount){
            $this->appReturn(0, '请输入正确的调价金额');
        }
        //退差价比例
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $percent = $this->mSetting->get('change_order_percent');
        if($percent > 0){
            $perAmount = sprintf('%.2f', ($info['product_amount']*(1-$percent/100)));//最低调价金额
            if($amount < $perAmount){
                $this->appReturn(0, '最低调价金额为:'.$perAmount);
            }
            //重新计算收益
            $diff = sprintf('%.2f',$info['product_amount'] - $amount);//差价

            $realityAmount = $info['reality_amount'] - $diff;
            $totalAmount = $info['total_amount'] - $diff;
            $webservice = round($amount*$info['percent']/100, 2); //平台服务费
            if($webservice < $info['min_order_web_amount']){
                $webservice = $info['min_order_web_amount'];
            }
            $bonus = isset($info['param']['bonus'])?$info['param']['bonus']:0;
            $merchantIncome = $realityAmount - $info['shipping_fee'] - $webservice + $bonus;//商家收入
            if($merchantIncome <= 0){
                $webIncome = $realityAmount - $info['shipping_fee'];
            }else{
                $webIncome = $webservice - $bonus; //平台收入
            }
            $data = array(
                'reality_amount' => $realityAmount,
                'change_amount' => $totalAmount,//调价后的总额
                'merchant_income' => $merchantIncome,
                'web_income' => $webIncome,
            );

            $this->db->trans_begin();//开启事务
            if(!($this->mOrder->save($data, '', $id))){
                $this->db->trans_rollback();
                $this->appReturn(0, '调价失败');
            }
            //更新用户账户余额
            $this->loadModel('ConsumerBuyModel', 'mBuy', 'consumer');
            $conBalLog = array(
                'type' => 3,
                'pay_type' => 1,
                'param' => $id,
                'consumer_id' => $info['consumer_id'],
                'status' => 2,
                'amount' => $diff,
                'addtime' => time(),
                'confirm_time' => time()
            );
            if(!($this->mBuy->save($conBalLog))){
                $this->db->trans_rollback();
                $this->appReturn(0, '调价失败');
            }

            $this->db->trans_commit();
            $this->appReturn(1, '调价成功');
        }else{
            $this->appReturn(0, '请设置差价百分比');
        }
    }
    /**
     * 立即接单
     */
    public function takeOrder(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('AdmShippingModel', 'mShipping', 'admin');
        //表单验证
        $vConf = array(
            array('id', '订单id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');

        //是否在营业时间端内
        $tBusiness = $this->mUser->getBusinessMerchant(array($this->userId));
        if(!isset($tBusiness[$this->userId])){
            $this->appReturn(0, '请在营业时间段内接单~');
        }
        //订单信息
        $info = $this->mOrder->getInfoForDeliveryman($id, $this->userId);
        if(date('Y-m-d', $info['expect_arrive_time']) != date('Y-m-d', time())){
            $this->appReturn(0, '您暂时不能接受此订单~');
        }
        //商品信息
        $productList = $this->mOrder->getOrderProductList($id, 0, $this->userId);
        if(!$productList){
            $this->appReturn(0, '订单不存在');
        }

        $product = array();
        $income = $info['deliveryman_income'];//配送员收入

        foreach ($productList as $pro){
            $product[] = array(
                'name' => $pro['name'].$pro['property_new'],
                'quantity' => $pro['quantity']
            );
        }

        if(!$info){
            $this->appReturn(0, '订单不存在');
        }

        //验证订单状态 及 配送方式
        if($info['status'] != 2 || $info['expense_type'] != 1){
            $this->appReturn(0, '订单状态错误');
        }

        $this->db->trans_begin();

        //减库存
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $reduce_stock = $this->mSetting->get('reduce_stock');
        if($reduce_stock == 2){//发货减库存
            $result = $this->mOrder->reduceStocks($id);
            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->appReturn(0, $result['message']);
            }
        }
        $merchantTakeTime = microtime(true);
        //保存订单信息

        if(!($this->mOrder->save(array('status' => 3,'print_status' => 2,'merchant_take_time'=>$merchantTakeTime), 0, $id))){
            $this->db->trans_rollback();
            $this->appReturn(0, '接单失败');
        }

        //赠送代金券
        if ( ! $this->GiveCoupon($id, $info['reality_amount'], $info['consumer_id'])){
            $this->db->trans_rollback();
            $this->appReturn(0, '代金劵赠送失败');
        }
        $this->db->trans_commit();
        //订单编号
        $count = $this->mOrder->getMerchantOrderCount($info['merchant_id'], $merchantTakeTime);
        //保存订单信息
        if(!($this->mOrder->save(array('merchant_day_index' => $count), 0, $id))){
            $this->ajaxReturn(0, '接单失败');
        }
        if($info['shipping_type'] == 2) {
            //配送员接单过期时间
            $rob_expect_time = $this->mSetting->get('rob_expect_time', 'deliveryman');
            //预计送达时间 = 预计送达时间  - 配送员过期时间 - 商家接单过期时间
            $timediff = $info['expect_arrive_time'] - time();
            $minute=floor($timediff%86400/60);
            $tTime = (int)getCustomConfig('expect_take_time') + $rob_expect_time;//预计送达时间
            $expect_arrive_time = $minute - $tTime;
            if($expect_arrive_time < 0){
                $expect_arrive_time = 0;
            }

            //生成运单
            $this->loadModel('DlnOrderModel', 'mDlnOrder', 'deliveryman');
            $distance = getDistance($info['shop_latitude'], $info['shop_longitude'], $info['latitude'], $info['longitude']);
            $result = $this->mDlnOrder->add($info['merchant_id'], $info['consumer_id'], 2, '#'.$count, $id, $info['province'],
                $info['city'], $info['county'], $info['shop_longitude'], $info['shop_latitude'], $info['merchant'],
                $info['shop_address'], $info['store_tel'], $info['contacts'], $info['mobile'], $info['address'],
                $info['longitude'], $info['latitude'], $product, $info['remark'], $expect_arrive_time,
                $income, $weight = 0, $distance);
            if ($result['status'] != 1) {
//                $this->db->trans_rollback();
                $this->appReturn(0, $result['message']);
            }
        }
        //记录订单操作日志
        if(!($this->mOrder->saveOrderLog($id, '待收货', '商家已受理', $this->port, $this->userId))){
//            $this->db->trans_rollback();
            $this->appReturn(0, '受理失败');
        }

        //推送消息
        $msgData = array(
            'title' => '商家已受理',
            'content' => '商家正在配送中',
            'addtime' => time(),
        );
        $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
        //删除消息查看记录
        $this->mMessage->deleteView($info['consumer_id'], 0, $id);
        if(!($this->mMessage->save($msgData, 0, $id))){
//            $this->db->trans_rollback();
            $this->appReturn(0, '消息保存失败');
        }
        jpush($msgData['title'], $msgData['content'], 1, array($info['jpush_code']), 3, $id, $info['expense_type']);

        //平台配送 通知配送员
        if($info['shipping_type'] == 2){
            $this->loadModel('DlnUserModel', 'mDlnUser', 'deliveryman');

            $distance = $this->mSetting->get('deliveryman_range', 'deliveryman');//配送员接单范围
            $distance = $distance>0 ? round($distance/1000,2):0;
            $dlnData = $this->mDlnUser->getDlnUser($info['latitude'], $info['longitude'], $distance);
            if($dlnData){
                $dlnJpush = array_column($dlnData, 'jpush_code');
                deliverymanJpush('新订单提醒','来新订单啦~赶快去抢单吧', 1, $dlnJpush, 0, 'new_order.mp3', 1);
            }
        }

        //小票信息

        $detail = $this->mOrder->getInfo($id, 0, $this->userId, false);
        $proData = array();
        if(isset($detail['param']) && $detail['param']){
            foreach ($detail['param'] as $k=>$v){
                $v = sprintf('%.2f', $v);
                if($k == 'bonus' && $v > 0){
                    $proData[] = array('keyword' => '红包', 'money' => '-￥'.$v);
                }elseif ($k == 'coupon' && $v> 0){
                    $proData[] = array('keyword' => '代金券', 'money' => '-￥'.$v);
                }elseif ($k == 'first_order_reduce' && $v> 0){
                    $proData[] = array('keyword' => '商家首单减免', 'money' =>'-￥'.$v);
                }elseif ($k == 'full_cut' && $v> 0){
                    $proData[] = array('keyword' => '满减活动', 'money' => '-￥'.$v);
                }elseif ($k == 'lunch_box_fee' && $v> 0){
                    $proData[] = array('keyword' => '打包费', 'money' => '￥'.$v);
                }elseif ($k == 'postal_card' && $v> 0){
                    $proData[] = array('keyword' => '包邮卡', 'money' => '-￥'.$v);
                }
            }
        }
        //配送费
        $proData[] = array('keyword' => '配送费', 'money' => '￥'.$detail['shipping_fee']);
        //收益
        $income = array(
            array('keyword' => '用户实付','money' =>'￥'.$detail['reality_amount']),
            array('keyword' => '平台服务费','money' =>'-￥'.sprintf('%.2f', $detail['web_service_amount'])),
        );

        if($detail['expense_type'] == 1){
            if($detail['shipping_type'] == 2){//平台配送
                $income[] = array('keyword' => '配送费','money' =>'-￥'.$detail['shipping_fee']);
            }
        }
        $count = '#'.$count;
        $n = (strtotime(date('Y').'-'.$detail['expect_arrive_time']) - time()) / 60;
        if ($n > getCustomConfig('arrive_time')){
            $count .= '预订单';
        }

        $aData = array(
            'id' => $detail['id'],
            'count' => $count,
            'code' => $detail['code'],
            'merchant' => $detail['merchant'],
            'portrait' => $detail['portrait'],
            'consumer_mobile' => $detail['consumer_mobile'],
            'consumer_portrait' => $detail['consumer_portrait'],
            'consumer' => $detail['consumer'],
            'status' => $detail['status'],
            'status_str' => $detail['status_str'],
            'tips' => $detail['tips'],
            'expect_take_time' => $detail['expect_take_time'],//接单有效时间
            'product_amount' => $detail['product_amount'],
            'total_amount' => $detail['total_amount'],
            'reality_amount' => $detail['reality_amount'],
            'remark' => $detail['remark'],
            'contacts' => $detail['contacts']?$detail['contacts']:'',
            'mobile' => $detail['mobile']?$detail['mobile']:'',
            'province' => $detail['province'],
            'city' => $detail['city'],
            'address_all' => $detail['address_all'],
            'pay_type_str' => $detail['pay_type_str'],
            'shipping_type' => $detail['shipping_type'],
            'expense_type' => $detail['expense_type'],
            'expense_type_str' => $detail['expense_type_str'],
            'addtime' => substr($detail['addtime'], 0, -3),
            'arrivetime' => $detail['expect_arrive_time'],//送达时间
            'web_service_amount' => $detail['web_service_amount'].'',
            'merchant_refound' => $detail['merchant_income'].'',
            'verification_bar_code' => $detail['verification_bar_code'],
            'verification_code' => $detail['verification_code'],
            'shortage_handing' => $detail['shortage_handing'],
            'param' => $proData,
            'income' => $income,
            'shipping_info' => (object)array(),
            'product' => $productList,
        );

        $this->appReturn(1,'接单成功', $aData);
    }

    /**
     * 自动打印小票
     */
    public function autoTakeOrder(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        //判断是否在营业时间段内
        $tBusiness = $this->mUser->getBusinessMerchant(array($this->userId));
        if(!isset($tBusiness[$this->userId])){
            $this->appReturn(1,' 小票信息', array());
        }
        $endtime = strtotime(date("Y-m-d",strtotime("+1 day"))) ;
        $this->db->select('o.id,o.expense_type, o.code, o.merchant_day_index as count, o.status, o.addtime, o.expect_arrive_time,
                            o.address,o.province_id,o.city_id,o.county_id, o.contacts, o.mobile, o.product_amount, o.total_amount, o.reality_amount,
                            o.shipping_type, o.pay_type, o.remark, o.param, o.percent, o.merchant_income, o.shortage_handing,
                            o.shipping_fee,o.change_amount,u.nickname,cu.mobile as consumer_mobile,cu.nickname as consumer')
                ->join($this->mConsumer->tbUser.' cu', 'cu.id = o.consumer_id')
                ->join($this->mUser->tbUser.' u', 'u.id = o.merchant_id')
            ->where('o.merchant_id', $this->userId)
            ->where(array('o.expect_arrive_time < ' => $endtime ))
            ->where(array('o.print_status' => 1,'o.status' => 3))
            ->order_by('o.id asc');

        $oData = $this->mOrder->getAll($this->mOrder->tbOrder.' o');

        if(!$oData){
            $this->appReturn(1,' 小票信息', array());
        }

        $orderIds = [];
        $printData = [];
        $locationIds = [];
        foreach ($oData as $k=>$v){
            if(!in_array($v['province_id'], $locationIds)){
                $locationIds[] = $v['province_id'];
            }
            if(!in_array($v['city_id'], $locationIds)){
                $locationIds[] = $v['city_id'];
            }
            if(!in_array($v['county_id'], $locationIds)){
                $locationIds[] = $v['county_id'];
            }
        }

        $tA = $this->mSett->getLocationNameByIds($locationIds);

        foreach ($oData as $k=>&$v){
            if(!in_array($v['id'], $orderIds)){
                $orderIds[] = $v['id'];
            }
            $printData[] = [
                'print_status' => 2,
                'id' => $v['id'],
            ];

            //占位数据
            $v['merchant'] = $v['nickname'];
            $v['portrait'] = '';
            $v['consumer_portrait'] = '';
            $v['tips'] = '';
            $v['province'] = isset($tA[$v['province_id']]) ? $tA[$v['province_id']]['name'] : '';
            $v['city'] = isset($tA[$v['city_id']]) ? $tA[$v['city_id']]['name'] : '';
            $v['county'] = isset($tA[$v['county_id']]) ? $tA[$v['county_id']]['name'] : '';
            $v['expense_type_str'] = '';
            $v['verification_bar_code'] = '';
            $v['verification_code'] = '';
            $v['address_all'] = ($v['province'] == $v['city'] ? $v['province'] : '')
                .$v['city'].$v['county'].$v['address'];
            unset($v['address']);
            $v['status_str'] = $this->mOrder->STATUS[$v['status']];
            $v['pay_type_str'] = $this->mOrder->PAY_TYPE[$v['pay_type']];
            $v['expect_take_time'] = '';//接单有效时间
            $v['addtime'] = date("Y-m-d H:i",$v['addtime']);
            $v['count'] = '#'.$v['count'];
            $n = ($v['expect_arrive_time'] - time()) / 60;
            if ($n > getCustomConfig('arrive_time')){
                $v['count'] .= '预订单';
            }
            $v['arrivetime'] = date("m-d H:i",$v['expect_arrive_time']);
            $v['product_amount'] = $v['change_amount'] > 0?$v['change_amount']:$v['product_amount'];
            $v['web_service_amount'] = $v['percent']? ($v['percent']*$v['product_amount']/100):0;//平台服务费
            //缺货处理
            $shortage = (object)array();
            if($v['shortage_handing']){
                $shortage = json_decode($v['shortage_handing'], true);
                if(!isset($shortage['value'])){
                    $shortage['value'] = 0;
                }
                $shortage['value'] = $this->mOrder->getShortage($shortage['value']);
            }
            $v['shortage_handing'] = $shortage;
            $proData = [];
            if(isset($v['param']) && $v['param']){
                $v['param'] = json_decode($v['param'], true);
                foreach ($v['param'] as $key=>$value){
                    $value = sprintf('%.2f', $value);
                    if($key == 'bonus' && $value > 0){
                        $proData[] = array('keyword' => '红包', 'money' => '-￥'.$value);
                    }elseif ($key == 'coupon' && $value> 0){
                        $proData[] = array('keyword' => '代金券', 'money' => '-￥'.$value);
                    }elseif ($key == 'first_order_reduce' && $value> 0){
                        $proData[] = array('keyword' => '商家首单减免', 'money' =>'-￥'.$value);
                    }elseif ($key == 'full_cut' && $value> 0){
                        $proData[] = array('keyword' => '满减活动', 'money' => '-￥'.$value);
                    }elseif ($key == 'lunch_box_fee' && $value> 0){
                        $proData[] = array('keyword' => '打包费', 'money' => '￥'.$value);
                    }elseif ($key == 'postal_card' && $value> 0){
                        $proData[] = array('keyword' => '包邮卡', 'money' => '-￥'.$value);
                    }
                }
            }
            //配送费
            if($v['expense_type'] == 1){
                $proData[] = array('keyword' => '配送费', 'money' => '￥'.$v['shipping_fee']);
            }

            //收益
            $income = array(
                array('keyword' => '用户实付','money' =>'￥'.$v['reality_amount']),
                array('keyword' => '平台服务费','money' =>'-￥'.sprintf('%.2f', $v['web_service_amount'])),
            );

            $v['param'] = $proData;
            $v['income'] = $income;
            $v['shipping_info'] = (object)array();
            $v['product'] = array();
        }

        //获取订单商品信息
        $this->db->select('op.id,op.order_id,op.product_id,p.name,op.price,op.variant_id,op.quantity,op.reality_amount,c.cat_name')
            ->join($this->mOrder->tbProduct. ' p', 'op.product_id = p.id')
            ->join($this->mOrder->tbProductCustomCategory. ' c', 'c.id = p.category_id')
            ->where_in('op.order_id', $orderIds);
        $tA = $this->mOrder->getAll($this->mOrder->tbOrderProduct.' op');

        $tData = array();
        foreach ($tA as $k=>&$v){
            if($v['cat_name']){
                $v['name'] = $v['cat_name'].':'.$v['name'];
            }
            $tData[$v['order_id']][]= $v;
        }

        foreach ($oData as $kk=>$vv){

            $oData[$kk]['product'] = $tData[$vv['id']]?$tData[$vv['id']]:'';
        }
        //改变订单打印状态
        if(!($this->mOrder->saveBatch($printData, '', '', 'id'))){
            $this->appReturn(0,'状态改变失败');
        }
        $this->appReturn(1,' 小票信息', $oData);
    }

    /**
     * 下单即可送代金劵
     */
    private function GiveCoupon($orderId, $realityAmount,$consumerId){
        if ( ! $orderId || !$consumerId){
            return false;
        }

        $this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
        $this->loadModel('MerchantPromotionModel', 'mMerPromotion','merchant');

        $tCoupon = $this->mMerPromotion->getCouponListByMerchantIds(array($this->userId));
        if ( ! $tCoupon){
            return true;
        }

        $tGiveCoupon = array();
        if (!isset($tCoupon[$this->userId])){
            //不存在
            return true;
        }

        if ($realityAmount >= $tCoupon[$this->userId]['receive']){
            //实际支付金额 > 代金劵领取条件
            //装入代金劵批量
            $tGiveCoupon[] = array(
                'merchant_id'	=> $this->userId,
                'consumer_id'	=> $consumerId,
                'order_id'		=> $orderId,
                'money'			=> $tCoupon[$this->userId]['money'],
                'valid_hour'	=> $tCoupon[$this->userId]['valid_hour'],
                'send_time'		=> time(),
                'status'		=> 1,
                'used_time'		=> 0,
                'condition'		=> $tCoupon[$this->userId]['condition'],
                'use_end_time'	=> time() + $tCoupon[$this->userId]['valid_hour'] * 3600,
            );
        }

        if ($tGiveCoupon){
            if ( ! $this->mPromotion->saveBatchCouponLog($tGiveCoupon)){
                return false;
            }
        }

        return true;
    }

    /**
     * 确认送达（商品配送订单）
     */
    public function delivery(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        //表单验证
        $vConf = array(
            array('id', '订单id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');

        $info = $this->mOrder->getInfo($id, 0, $this->userId, true);

        if($info['status'] != 3 || $info['expense_type'] != 1 || $info['shipping_type'] != 1){
            $this->appReturn(0, '订单不符合送达');
        }

        $this->db->trans_begin();
        //核销订单
        $result = $this->mOrder->_confirmReceipt($id, '确认送达', $this->userId, $this->port, $info['consumer_id']);
        if($result['status'] == 0){
            $this->db->trans_rollback();
            $this->appReturn(0, $result['message']);
        }
        //减库存
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $reduce_stock = $this->mSetting->get('reduce_stock');

        if($reduce_stock == 2){//发货减库存
            $result = $this->mOrder->reduceStocks($id);

            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->appReturn(0, $result['message']);
            }
        }
        //增加销量
        $productList = $this->mOrder->getOrderProductList($id);

        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        foreach ($productList as $v){
            if ($v['variant_id'] > 0){
                $query = $this->mProduct->savePropertyVariant(array('sale_quantity'=>$v['v_sale_quantity'] + $v['quantity']),$v['product_id'],$v['variant_id']);
                if(!$query){
                    $this->db->trans_rollback();
                    $this->appReturn(0,'销量增加失败');
                }
            }
            $qy = $this->mProduct->save(array('sale_quantity'=>$v['sale_quantity']+ $v['quantity']), $v['product_id']);
            if(!$qy){
                $this->db->trans_rollback();
                $this->appReturn(0,'销量增加失败');
            }
        }
        //用户推送消息
        $msgData = array(
            'title' => '订单已送达',
            'content' => '订单已送达,请当面验收检查',
            'addtime' => time(),
        );
        $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
        //删除消息查看记录
        $this->mMessage->deleteView($info['consumer_id'], 0, $id);
        if(!($this->mMessage->save($msgData, 0, $id))){
            $this->db->trans_rollback();
            $this->appReturn(0, '消息保存失败');
        }
        jpush($msgData['title'], $msgData['content'], 1, array($info['jpush_code']), 3, $id, $info['expense_type']);

        //商家推送消息
        $this->loadModel('merchantMessageModel', 'mMerMsg', 'merchant');
        //删除消息查看记录
        $this->mMerMsg->deleteView($this->userId, 0, $id);
        if(!($this->mMerMsg->save($msgData, 0, $id))){
            $this->db->trans_rollback();
            $this->appReturn(0, '消息保存失败');
        }
        MerchantJpush($msgData['title'], $msgData['content'], 1, array($this->userJpushCode), 3, $id);

        $this->db->trans_commit();
        $this->appReturn(1,'订单已送达');

    }

    /**
     * 确认核销订单
     */
    public function checkOrder(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        //表单验证
        $vConf = array(
            array('id', '订单id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');

        //订单信息
        $info = $this->mOrder->getInfo($id, 0, $this->userId, true);
        if(!$info){
            $this->appReturn(0, '无效的核销码');
        }

        //验证订单状态 及 配送方式
        if($info['status'] != 3 || $info['expense_type'] != 2){
            $this->appReturn(0, '订单状态错误');
        }
        $this->db->trans_begin();
        //核销订单
        $result = $this->mOrder->_confirmReceipt($id, '核销订单', $this->userId, $this->port, $info['consumer_id']);
        if($result['status'] == 0){
            $this->db->trans_rollback();
            $this->appReturn(0, $result['message']);
        }
        //减库存
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $reduce_stock = $this->mSetting->get('reduce_stock');

        if($reduce_stock == 2){//发货减库存
            $result = $this->mOrder->reduceStocks($id);

            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->appReturn(0, $result['message']);
            }
        }
        //增加销量
        $productList = $this->mOrder->getOrderProductList($id);

        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        foreach ($productList as $v){
            if ($v['variant_id'] > 0){
                $query = $this->mProduct->savePropertyVariant(array('sale_quantity'=>$v['v_sale_quantity'] + $v['quantity']),$v['product_id'],$v['variant_id']);
                if(!$query){
                    $this->db->trans_rollback();
                    $this->appReturn(0,'销量增加失败');
                }
            }
            $qy = $this->mProduct->save(array('sale_quantity'=>$v['sale_quantity']+ $v['quantity']), $v['product_id']);
            if(!$qy){
                $this->db->trans_rollback();
                $this->appReturn(0,'销量增加失败');
            }
        }
        //用户推送消息
        $msgData = array(
            'title' => '订单已核销',
            'content' => '订单核销成功',
            'addtime' => time(),
        );
        $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
        if(!($this->mMessage->save($msgData, 0, $id))){
            $this->db->trans_rollback();
            $this->appReturn(0, '消息保存失败');
        }

        //删除消息查看记录
        $this->mMessage->deleteView($info['consumer_id'], 0, $id);
        if(!($this->mMessage->save($msgData, 0, $id))){
            $this->db->trans_rollback();
            $this->appReturn(0, '消息保存失败');
        }
        jpush($msgData['title'], $msgData['content'], 1, array($info['jpush_code']), 3, $id, $info['expense_type']);

        //商家推送消息
        $this->loadModel('merchantMessageModel', 'mMerMsg', 'merchant');
        //删除消息查看记录
        $this->mMerMsg->deleteView($this->userId, 0, $id);
        if(!($this->mMerMsg->save($msgData, 0, $id))){
            $this->db->trans_rollback();
            $this->appReturn(0, '消息保存失败');
        }
        MerchantJpush($msgData['title'], $msgData['content'], 1, array($this->userJpushCode), 3, $id);

        $this->db->trans_commit();
        $this->appReturn(1,'核销成功');
    }

    /**
     * 核销记录
     */
    public function checkOrderList(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        //表单验证
        $vConf = array(
            array('page', '页码', 'required|is_natural_no_zero')
        );
        $this->formDataValidation($vConf);

        $page = (int)post('page');
        //核销记录
        $list = $this->mOrder->appGetMerchantOrderList($this->userId, 2, 0, $page, true);

        //今日核销 今日收益
        $start = strtotime(date('Y-m-d'));
        $end = $start + 86399;

        $today = $this->mOrder->merchantCheckOrderStatistical($this->userId, $start, $end);

        $data = array(
            'total' => $today['total'],
            'amount' => $today['amount']?$today['amount']:'0',
            'list' => $list,
        );
        $this->appReturn(1, '', $data);
    }

	/**
     * 售后订单列表
     */
	public function afterSaleList(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        //表单验证
        $vConf = array(
            array('status', '售后状态', 'required|in_list[0,4,2,3]'),
            array('page', '页码', 'required|is_natural_no_zero')
        );
        $this->formDataValidation($vConf);

        $page = (int)post('page');
        $status = (int)post('status');

        $tA = $this->mOrder->appGetServiceList(0, $this->userId, $page, $status);

        $this->appReturn(1, '', $tA);
    }

    /**
     * 售后订单详情
     */
    public function afterSaleDetail(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('ConsumerUserModel', 'mCuser', 'consumer');
        $this->loadModel('AdmSettingModel', 'mAdm', 'admin');
        //表单验证
        $vConf = array(
            array('id', '售后id', 'required|is_natural_no_zero')
        );
        $this->formDataValidation($vConf);
        $service_id = post('id');

        $info = $this->mOrder->getServiceInfo('', 0, 0, 0, $this->userId, $service_id);

        if(!$info){
            $this->appReturn(0, '售后订单不存在');
        }
        //订单商品数据
        $product = $this->mOrder->getProductList($info['order_id'],  0, 0,$this->userId);
        if ( ! $product){
            $this->appReturn(0,'订单商品数据为空');
        }
        $info['product'] = $product;
        //平台服务电话
        $info['web_service_tel'] = $this->mAdm->get('web_merchant_service_tel');
        //用户信息
        $consumer = $this->mCuser->getInfo($info['consumer_id']);
        $info['consumer_mobile'] = isset($consumer['mobile'])?$consumer['mobile']:'';
        $info['easemob_name'] = isset($consumer['jpush_code'])?$consumer['jpush_code']:'';
        $info['nickname'] = isset($consumer['nickname'])?$consumer['nickname']:'';
        $info['portrait'] = isset($consumer['portrait'])?$consumer['portrait']:'';
        //改变消息状态
        $this->loadModel('MerchantMessageModel', 'mMessage');
        $message = $this->mMessage->getInfo(0, $this->userId, 0, $service_id);
        if ($message){
            // 添加消息查看记录
            if ($message['viewed'] == 1) {
                $messageData = array(
                    'merchant_id' => $this->userId,
                    'message_id' => $message['id'],
                    'is_delete' => 1,
                    'addtime' => time(),
                );

                $viewed = $this->mMessage->saveView($messageData);
                if (!$viewed) {
                    $this->appReturn(0, '添加消息查看记录失败');
                }
            }
        }

        $this->appReturn(1, '', $info);
    }

    /**
     * 售后同意退款
     */
    public function agreeRefund(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('ConsumerUserModel', 'mCuser', 'consumer');
        $this->loadModel('MerchantBalanceModel', 'mBalance', 'merchant');

        //表单验证
        $vConf = array(
            array('code', '售后单号', 'required')
        );
        $this->formDataValidation($vConf);

        $code = trim(post('code'));

        $info = $this->mOrder->getServiceInfo($code, 0, 0, 0, $this->userId);
        if(!$info){
            $this->appReturn(0, '售后订单不存在');
        }
        //判断售后订单状态
        if($info['status'] != 3){
            $this->appReturn(0, '请刷新后操作');
        }

        $this->db->trans_begin();
        $result = $this->mOrder->_agreeRefund($info);
        if($result['status'] == 0){
            $this->db->trans_rollback();
            $this->appReturn(0, $result['message']);
        }
        //保存售后信息
        $sData = array(
            'complete_remark' => '商家同意退款',
            'complete_time' => time(),
            'status' => 2,
        );
        if(!($this->mOrder->saveService($sData, $code))){
            $this->db->trans_rollback();
            $this->appReturn(0, '保存失败');
        }

        //订单商品全部售后完成 改变订单状态为交易关闭
        if(!($this->mOrder->save(array('status' => 6), 0, $info['order_id']))){
            $this->db->trans_rollback();
            $this->appReturn(0, '保存失败');
        }

        $this->db->trans_commit();
        $this->appReturn(1, '售后成功');
    }

    /**
     * 售后拒绝退款
     */
    public function refuseRefund(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        //表单验证
        $vConf = array(
            array('code', '售后单号', 'required'),
            array('reason', '拒绝退款原因', 'required'),
        );
        $this->formDataValidation($vConf);

        $code = trim(post('code'));
        $reason = trim(post('reason'));

        $info = $this->mOrder->getServiceInfo($code, 0, 0, 0, $this->userId);
        if(!$info){
            $this->appReturn(0, '售后订单不存在');
        }
        //判断售后订单状态
        if($info['status'] != 3){
            $this->appReturn(0, '请刷新后操作');
        }
        $data = array(
            'complete_remark' => $reason,
            'complete_time' => time(),
            'status' => 4,
        );
        $this->db->trans_begin();
        //保存售后信息
        if(!($this->mOrder->saveService($data, $code))){
            $this->db->trans_rollback();
            $this->appReturn(0, '保存失败');
        }
        //推送消息
        $this->mOrder->_orderServiceMessage($info, 2, $reason);

        $this->db->trans_commit();
        $this->appReturn(1, '保存成功');
    }
}